package club.dmyang.service;

import club.dmyang.common.enums.RespCodeEnums;
import club.dmyang.common.exception.HyBlogException;
import club.dmyang.dao.ArticleMapper;
import club.dmyang.dao.RelatiTagArtiMapper;
import club.dmyang.entity.ArchiveCount;
import club.dmyang.entity.Article;
import club.dmyang.entity.ArticleWithBLOBs;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by brss on 2018/7/14.
 */
@Service("articleService")
public class ArticleServiceImpl implements ArticleService {

    private static final Logger LOGGER = LoggerFactory.getLogger(ArticleServiceImpl.class);

    @Autowired
    private ArticleMapper articleMapper;
    @Autowired
    private RelatiTagArtiMapper relatiTagArtiMapper;

    /**
     * 查询表中category_id=categoryId的文章的数目
     * (用于删除分类时，判断某分类下是否有文章)
     *
     * @param categoryId
     */
    @Override
    public Integer findNumByCategoryId(Integer categoryId) {
        return articleMapper.selectNumByCategoryId(categoryId);
    }

    /**
     * 查询tag_article表中，tid=tagId的数目
     * (用于删除标签时，判断某标签下是否有文章)
     *
     * @param tagId
     */
    @Override
    public Integer findNumByTagId(Integer tagId) {
        return relatiTagArtiMapper.selectNumByTagId(tagId);
    }


    /**
     * 查询一篇文章
     *
     * @param aid
     * @return
     */
    @Override
    public ArticleWithBLOBs findOneArticle(Integer aid) {
        ArticleWithBLOBs articleWithBLOBs = articleMapper.selectByPrimaryKey(aid);
        return articleWithBLOBs;
    }

    /**
     * 根据页数(page)和每页容量(limit)查询文章列表
     * 不查询长文本
     *
     * @param page
     * @param limit
     * @return
     */
    @Override
    public List<Article> findArticlesByPageAndLimit(Integer page, Integer limit) {
        if ( page < 1 || limit < 1 ){
            LOGGER.error("page或limit错误！[ page = "+page + "limit = "+limit + "]");
            throw new HyBlogException(RespCodeEnums.GLOBAL_CODE_PARAMETER_ERROR);
        }
        List<Article> articles = articleMapper.selectByStartAndLimit((page - 1) * limit, limit);
        return articles;
    }


    /**
     * 查询数据库中所有文章的个数
     * （用于分页插件计算一个有多少页）
     *
     * @return
     */
    @Override
    public int findAllNums() {
        return articleMapper.selectAllNum();
    }

    /**
     * 根据页数(page)和每页容量(limit)查询【最新】文章列表
     *
     * @param page
     * @param limit
     * @return
     */
    @Override
    public List<Article> findNewestArticlesByPageAndLimit(Integer page, Integer limit) {
        if ( page < 1 || limit < 1 ){
            LOGGER.error("page或limit错误！[ page = "+page + "limit = "+limit + "]");
            throw new HyBlogException(RespCodeEnums.GLOBAL_CODE_PARAMETER_ERROR);
        }
        List<Article> articleList = articleMapper.findNewestArticlesByPageAndLimit((page - 1) * limit, limit);
        return articleList;
    }

    /**
     * 由主键更新文章（选择性）
     *
     * @param article
     * @return
     */
    @Override
    public int updateByPkSeletive(ArticleWithBLOBs article) {
        return articleMapper.updateByPrimaryKeySelective(article);
    }

    /**
     * 根据标分类id查找文章（分页）
     *
     * @param cid
     * @param page
     * @param Limit @return
     */
    @Override
    public List<Article> findByCidWithPgAndLimit(Integer cid, Integer page, Integer Limit) {
        return articleMapper.findByCidWithPgAndLimit(cid,(page-1)*Limit,Limit);
    }

    /**
     * 根据标签Id查找文章（分页）
     *
     * @param tid
     * @param page
     * @param Limit @return
     */
    @Override
    public List<Article> findByTidWithPgAndLimit(Integer tid, Integer page, Integer Limit) {
        return articleMapper.findByTidWithPgAndLimit(tid,(page-1)*Limit,Limit);
    }

    /**
     * 点赞
     * 如何防止恶意点赞！！！！
     * @param aid
     * @return
     */
    @Override
    public synchronized int voteOneArticle(Integer aid) {
        //查询出文章信息
        ArticleWithBLOBs dbArticle = articleMapper.selectByPrimaryKey(aid);
        ArticleWithBLOBs article = new ArticleWithBLOBs();
        article.setAid(aid);
        article.setVotes(dbArticle.getVotes()+1);//在数据库中原有点赞数加一
        int i = articleMapper.updateByPrimaryKeySelective(article);
        return i;
    }

    /**
     * 获取归档信息
     * key : 2018_8
     * value : result list
     *
     * @return
     */
    @Override
    public Map<String, List<Article>> getArchive() {
        //返回的Map
        Map<String, List<Article>> result = new LinkedHashMap<>();
        //获取哪些年月有文章发表，文章个数
        List<ArchiveCount> countList = articleMapper.selectArchiveCount();
        for ( ArchiveCount a : countList ){
            List<Article> articles = articleMapper.selectByYearAndMonth(a.getYear(), a.getMonth());
            result.put(a.getYear()+"-"+a.getMonth() ,articles);
        }
        return result;
    }

    /**
     * 由关键字搜索文章
     *
     * @param keyword
     * @param page
     * @param limit   @return
     */
    @Override
    public List<Article> searchByKeyword(String keyword, Integer page, Integer limit) {
        String k = "%"+ keyword +"%";
        List<Article> articleList = articleMapper.selectByKeyword(k, (page - 1) * limit, limit);
        return articleList;
    }

    /**
     * 查询含有这个关键字的总文章个数（用于计算分页数）
     *
     * @param keyword
     * @return
     */
    @Override
    public int findNumByKeyword(String keyword) {
        String k = "%"+ keyword +"%";
        return articleMapper.selectNumByKeyword(k);
    }

}
